package com.ffs.template.util;

import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;

/**
 * Velocity工具
 *
 * @author ffs80
 */
@SuppressWarnings("unused")
public class VelocityUtil {

    private static final Properties properties = new Properties();

    static {
        properties.setProperty(Velocity.INPUT_ENCODING, "UTF-8");
        properties.setProperty(Velocity.OUTPUT_ENCODING, "UTF-8");
        properties.setProperty(Velocity.ENCODING_DEFAULT, "UTF-8");
        //properties.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
        Velocity.init(properties);
    }

    /**
     * 文件输出
     *
     * @param context      Velocity数据容器
     * @param templatePath 模板路径
     * @param outPath      文件输出路径
     */
    public static void outFile(VelocityContext context, String templatePath, String outPath) throws IOException {
        //获取模板对象
        Template template = Velocity.getTemplate(templatePath);
        String dirPath = outPath.substring(0, outPath.lastIndexOf('/') + 1);
        File dir = new File(dirPath);
        //文件输出路径
        if (!dir.exists()) {
            boolean mkdirs = dir.mkdirs();
        }
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outPath), StandardCharsets.UTF_8));

        if (template != null) {
            template.merge(context, writer);
        }

        System.out.println("out file to:" + outPath);
        writer.flush();
        writer.close();
    }
}
